package puan.com.weighBox.activity;

import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.evan.ble.BleManager;
import com.evan.ble.data.BleDevice;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import puan.com.weighBox.BluetoothService;
import puan.com.weighBox.Constant;
import puan.com.weighBox.MainEvent;
import puan.com.weighBox.R;
import puan.com.weighBox.adapter.BluetoothListAdapter;
import puan.com.weighBox.base.BaseActivity;
import puan.com.weighBox.bean.OrderBean;
import puan.com.weighBox.presenter.MainActivityPresenter;
import puan.com.weighBox.viewInterface.IMainView;


public class MainActivity extends BaseActivity implements View.OnClickListener, IMainView {


    private RelativeLayout rlSongDian, rlKaiXiang, rlXunJian, rlMore;
    private MainActivityPresenter presenter;
    private List<BleDevice> bluetoothDeviceList = new ArrayList();
    private static int REQUEST_OPEN_BLUETOOTH_CODE = 11;
    private Dialog bluetoothListDialog;
    private boolean isScanning = false;//是否正在扫描
    private BluetoothListAdapter bluetoothListAdapter;
    private RelativeLayout rlProgress;
    private Button btnScan;
    private EditText etBoxNum;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnScan:
                String order = etBoxNum.getText().toString();
//                OrderBean orderBean = new OrderBean(Constant.ACTION_SETTING, Constant.ORDER_SETTING);
                OrderBean orderBean = new OrderBean(Constant.ACTION_SETTING, order);
                EventBus.getDefault().post(new MainEvent<>(MainEvent.DO_SEND_DATA, orderBean));
                break;
            case R.id.rlSongDian:

                break;
            case R.id.rlKaiXiang:

                break;
            case R.id.rlXunJian:
                ActivityUtils.startActivity(new Intent(this, XunJianActivity.class));
                break;
            case R.id.rlMore:
                ActivityUtils.startActivity(new Intent(this, AdminActivity.class));
                break;
            default:
                break;
        }
    }

    @Override
    public int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(null);
        ((TextView) findViewById(R.id.tvToolTitle)).setText("首页");

        rlSongDian = findViewById(R.id.rlSongDian);
        rlKaiXiang = findViewById(R.id.rlKaiXiang);
        rlXunJian = findViewById(R.id.rlXunJian);
        rlMore = findViewById(R.id.rlMore);
        btnScan = findViewById(R.id.btnScan);
        etBoxNum = findViewById(R.id.etBoxNum);

        rlSongDian.setOnClickListener(this);
        rlKaiXiang.setOnClickListener(this);
        rlXunJian.setOnClickListener(this);
        rlMore.setOnClickListener(this);
        btnScan.setOnClickListener(this);
    }

    @Override
    public void initData() {
        presenter = new MainActivityPresenter(this);
        initBluetooth();
    }

    private void initBluetooth() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "该不支持BLE", Toast.LENGTH_SHORT).show();
            return;
        }

        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_OPEN_BLUETOOTH_CODE);
        } else {
            startAndBindService();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_OPEN_BLUETOOTH_CODE && resultCode == RESULT_OK) {
            startAndBindService();
        }
    }

    private void startAndBindService() {
        Intent intent = new Intent(this, BluetoothService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            showBluetoothListDialog();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("lmsg", "onServiceDisconnected: 服务断开连接");
        }
    };

    /**
     * 显显show蓝牙列表dialog
     */
    private void showBluetoothListDialog() {
        View view = View.inflate(MainActivity.this, R.layout.dialog_bluetooth_list, null);
//        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_bluetooth_list, null, false);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        RecyclerView rcvBluetoothList = view.findViewById(R.id.rcvBluetoothList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rcvBluetoothList.setLayoutManager(layoutManager);
        bluetoothListAdapter = new BluetoothListAdapter(this, bluetoothDeviceList);
        rcvBluetoothList.setAdapter(bluetoothListAdapter);
        bluetoothListDialog = builder.create();
        bluetoothListDialog.show();
        final ImageView ivBluetoothIcon = view.findViewById(R.id.ivBluetoothIcon);
        rlProgress = view.findViewById(R.id.rlProgress);
        view.findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothListDialog.dismiss();
            }
        });
        final TextView tvScan = view.findViewById(R.id.tvScan);
        tvScan.setOnClickListener(view1 -> {
            if (isScanning) {
                EventBus.getDefault().post(new MainEvent<>(MainEvent.DO_SCAN_BLUETOOTH, true));
                tvScan.setText("扫描蓝牙");
                rlProgress.setVisibility(View.GONE);
            } else {
                EventBus.getDefault().post(new MainEvent<>(MainEvent.DO_SCAN_BLUETOOTH, false));
                tvScan.setText("正在扫描");
                rlProgress.setVisibility(View.VISIBLE);
            }
            isScanning = !isScanning;
        });
        bluetoothListAdapter.setOnBluetoothItemClickListener(new BluetoothListAdapter.OnBluetoothItemClickListener() {
            @Override
            public void onItemClick(BleDevice bleDevice) {
                EventBus.getDefault().post(new MainEvent<>(MainEvent.DO_CONNECT_BLUETOOTH, bleDevice));
                ivBluetoothIcon.setBackgroundResource(R.drawable.play_ble_connect_anim);
                AnimationDrawable animation = (AnimationDrawable) ivBluetoothIcon.getBackground();
                animation.start();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThreadEvent(MainEvent mainEvent) {
        if (mainEvent.getCode() == MainEvent.DO_CONNECT_BLUETOOTH_SUCCESS) {
            if (bluetoothListDialog != null) {
                bluetoothListDialog.dismiss();
            }
            //连接成功之后发送设置指令
//            OrderBean orderBean = new OrderBean(Constant.ACTION_SETTING,  Constant.ORDER_SETTING);
//            EventBus.getDefault().post(new MainEvent<>(MainEvent.DO_SEND_DATA, orderBean));
        } else if (mainEvent.getCode() == MainEvent.NOTIFY_BLUETOOTH_LIST) {
            if (rlProgress != null) {
                rlProgress.setVisibility(View.GONE);
            }
            BleDevice device = (BleDevice) mainEvent.getValue();
            bluetoothDeviceList.add(device);
            bluetoothListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
